package com.zlyx.easy.http.handlers;

import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.zlyx.easy.core.handler.annotations.Brancher;
import com.zlyx.easy.core.utils.JsonUtils;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.http.executor.HttpExecutor;
import com.zlyx.easy.http.models.RequestModel;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
@Brancher(todo = { "处理POST请求" }, value = "POST")
public class PostMappingHandler extends AbstractMappingHandler {

	public PostMappingHandler(@Autowired(required = false) HttpExecutor httpService) {
		super(httpService);
	}

	@Override
	public Object handleMapping(RequestModel rm) throws Exception {
		HttpHeaders headers = rm.getHeaders();
		if (headers == null && rm.getMediaType() != null) {
			headers = new HttpHeaders();
			headers.set(HttpHeaders.CONTENT_TYPE, rm.getMediaType());
		}
		String url = rm.getUrl();
		MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
		if (rm.getParams() != null) {
			for (Entry<String, Object> entry : rm.getParams().entrySet()) {
				if (entry.getValue() != null) {
					String key = entry.getKey();
					String value = StringUtils.valueOf(entry.getValue());
					if (url.contains(":" + key)) {
						url = url.replace(":" + key, "" + value);
					} else if (url.contains("{" + key + "}")) {
						url = url.replace("{" + key + "}", "" + value);
					} else {
						multiValueMap.add(key, value);
					}
				}
			}
		}
		HttpEntity<?> entity = null;
		if (headers != null && MediaType.APPLICATION_JSON_UTF8.isCompatibleWith(headers.getContentType())) {
			entity = new HttpEntity<>(JsonUtils.toJson(rm.getParams()), headers);
		} else {
			entity = new HttpEntity<>(multiValueMap, headers);
		}
		return httpService.excute(rm, url, entity, rm.getReturnType());
	}
}
